import random
import csv
import numpy as np


# 使用一个三元组来表示交易
def get_shard(tx, shardNum):
    return tx[0] % shardNum


def get_random_transaction(nodeNum):
    s = random.randint(0, nodeNum - 1)  # 发送者
    r = random.randint(0, nodeNum - 1)  # 接收者
    while s == r:
        r = random.randint(0, nodeNum - 1)
    v = 1  # 交易金额
    return [s, r, v]


# 获取一批交易
def generate_patch_tx(NodeNum, patch):
    res = []
    for i in range(int(patch)):
        res.append(get_random_transaction(NodeNum))

    return res


# 简单版 不考虑跨分片交易的分片
def transaction_shard(transactions, shardNum):
    sharded_tx = [[] for i in range(shardNum)]

    for tx in transactions:
        sid = get_shard(tx, shardNum)
        sharded_tx[sid].append(tx)

    return sharded_tx


# 交易保存成文件
def transaction_save(txs):
    with open('./tx.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([0,0,0])
        for row in txs:
            writer.writerow(row)


